var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var SessionStore = require("session-mongoose")(express);
/*var store = new SessionStore({
    url:"mongodb://localhost/session",
    interval:120000
});*/
var movie = require('./routes/movie');

var flash = require('connect-flash');


//用connect-mongo连接数据库
var MongoStore = require('connect-mongo')(express);
var settings = require('./models/setting');




var routes = require('./routes');
var users = require('./routes/user');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.methodOverride());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
//app.use(express.cookieSession({secret : 'fens.me'}));
/*app.use(express.session({
    secret : 'fens.me',
    store: store,
    cookie: { maxAge: 900000 }
}));*/
app.use(express.session({
    secret : settings.cookieSecret,
    store: new MongoStore({
        db:settings.db
    })
}));

app.use(flash());

app.use(function(req, res, next){
    res.locals.user = req.session.user;

    var err = req.session.error;
    res.locals.message = '';
    if(err){
        res.locals.message = '<div class="alert alert-error">' + err + '</div>';
    }

    next();
});


app.use(function (req, res, next) {
    res.locals.user = req.session ? req.session.user : '';
    res.locals.error = req.session ? req.session.err : null;
    res.locals.success = req.session ? req.session.success : null;
    res.locals.session = req.session ? req.session : null;
    next();
});

app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));



app.get('/', routes.index);
app.get('/users', users.list);

app.get('/reg', routes.regst);
app.post('/reg', routes.regster);


app.all('/login', notAuthentication);
app.get('/login', routes.login);
app.post('/login', notAuthentication);
app.post('/login', routes.doLogin);

app.get('/logout', authentication);
app.get('/logout', routes.logout);

app.get('/home', authentication);
app.get('/home', routes.homepage);

app.all('/addblog', authentication);
app.get('/addblog',routes.addblog);
app.post('/addblog',routes.doAddblog);
app.get('/u/:user',routes.publishBlog);

//app.get('/movie/:name',movie.movieAdd);
//app.get('/movie/json/:name',movie.movieJson);

function authentication(req,res,next){
    if(!req.session.user){
        req.flash('error','未登录，请先登录！');
        //req.session.error = '请先登录';
        return res.redirect('/login');
    }
    next();
}

function notAuthentication(req,res,next){
    if(req.session.user){
        req.flash('error','已登录！');
        //console.log(req.session.user);
       // req.session.error = '已登录';
        return res.redirect('/');
    }
    next();
    //console.log(req.session.user);
}



/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});





/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.render('error', {
        message: err.message,
        error: {}
    });
});



/*app.dynamicHelpers({
    user:function(req,res){
        return req.session.user;
    },
    error:function(req,res){
        var err = req.flash('error');
        if(err.length){ return err}else{return null}
    },
    success:function(req,res){
        var succ = req.flash('success');
        if(succ.length){return succ;}else{ return null}
    }

});*/

module.exports = app;
